package com.itjeffrey.autocode.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import com.itjeffrey.autocode.util.IdWorker;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * 自定义配置类
 *
 * @From: Jeffrey
 * @Date: 2020/11/8
 */
@Configuration
public class CustomConfig {

    /**
     * Mybatis-plus SQL性能分析插件，打印SQL执行时间及格式化语句
     * 注：不建议生产环境使用
     * @return
     */
    @Bean
    @Profile(value = {"dev"})
    public PerformanceInterceptor performanceInterceptor(){
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        //sql是否格式化
        //performanceInterceptor.setFormat(true);
        //sql最大执行时间，超过则自动停止运行
        //performanceInterceptor.setMaxTime(6000);
        return performanceInterceptor;
    }

    /**
     * Mybatis-plus 分页插件
     * @return
     */
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }

    /**
     * 分布式自增长ID
     * @return
     */
    @Bean
    public IdWorker idWorker() {
        return new IdWorker(1, 1);
    }

    /**
     * 对websocket进行检测，缺省会导致websocket无法正常运行
     * （单元测试时，此处需注释，否则抛出异常 IllegalStateException: javax.websocket.server.ServerContainer not available）
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    /**
     * security密码加密器
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 通用文件上传解析器
     * @return
     */
    @Bean(name = "multipartResolver")
    public CommonsMultipartResolver multipartResolver(){
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setDefaultEncoding("UTF-8");
        resolver.setMaxInMemorySize(-1);
        return resolver;
    }
}
